﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.SmartDevice.MultiTargeting.Connectivity;
using Microsoft.VisualStudio.Shell;
using VirtualMachines;
using AppRes = WindowsPhoneCommands.Resources;
using System.Collections.Generic;
using ContextMenu = System.Windows.Controls.ContextMenu;
using Cursors = System.Windows.Input.Cursors;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using UserControl = System.Windows.Controls.UserControl;
using Microsoft.VisualStudio.Shell.Interop;
using System.Windows.Media.Animation;
using System.ComponentModel;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class MainControl : UserControl
    // ReSharper restore RedundantExtendsListEntry
    {

        #region fields

        internal readonly DispatcherTimer Timer;

        private bool _loaded;
        private readonly ToolWindowPane _parentWindow;
        private readonly Dictionary<string, IsoFilesView> _isoFiles;
        private Storyboard _updatedStoryboard;

        #endregion

        #region constructor

        internal WindowsPhoneCommandsPackage Package
        {
            get
            {
                return (WindowsPhoneCommandsPackage)_parentWindow.Package;
            }
        }

        public MainControl()
            : this(null)
        {

        }

        public MainControl(ToolWindowPane parentWindow)
        {
            _parentWindow = parentWindow;

            InitializeComponent();

            _isoFiles = new Dictionary<string, IsoFilesView>();

            Timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
            Timer.Tick += TimerTick;

            BntUpdated.Visibility = Visibility.Collapsed;

            Loaded += MainControlLoaded;

        }

        private void MainControlLoaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {

                //EnvPhoneDevice.ListenVsTargetDevice(Package.EnvDte);
                //EnvPhoneDevice.ChangedTargetDevice += EnvPhoneDeviceChangedTargetDevice;

                CelPhoneManufature.Text = EnvPhoneDevice.CurrentTargetDevice(Package.PhoneDevice);
                CelPhoneVersion.Text = EnvPhoneDevice.PhoneVersion(Package.PhoneDevice);

                var overflowGrid = toolbar.Template.FindName("OverflowGrid", toolbar) as FrameworkElement;
                if (overflowGrid != null)
                {
                    overflowGrid.Visibility = Visibility.Collapsed;
                }

                ActCopysel.Foreground = VsTheming.GetWindowDisabledText();
                ActDeletesel.Foreground = VsTheming.GetWindowDisabledText();
                InstalledTitle.Foreground = VsTheming.GetWindowText();
                UpdatedText.Foreground = VsTheming.GetColorError();

                // Look for update async
                var bw = new BackgroundWorker();
                bw.DoWork += BwDoWork;
                bw.RunWorkerCompleted += BwRunWorkerCompleted;

                // Animate updated button
                var updDoubleAnimation = new DoubleAnimation
                {
                    From = 0,
                    To = 1.0,
                    Duration = new Duration(TimeSpan.FromMilliseconds(500)),
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };

                _updatedStoryboard = new Storyboard();
                _updatedStoryboard.Children.Add(updDoubleAnimation);
                Storyboard.SetTargetName(updDoubleAnimation, UpdatedText.Name);
                Storyboard.SetTargetProperty(updDoubleAnimation, new PropertyPath(OpacityProperty));
                bw.RunWorkerAsync();

            }
            ShowInfoEnvDevice();
            ChangeBntConnect();
            UpdateMenu(Package.TotalPhoneProjects > 0);
            _loaded = true;


        }

        #endregion

        #region internal methods

        internal void ShowInfoEnvDevice()
        {
            CelPhoneMsg.Text = Package.StatusConnect;
            CelPhoneVersion.Text = EnvPhoneDevice.PhoneVersion(Package.PhoneDevice);
        }

        internal void DisconnectDebug()
        {
            var devSelected = EnvPhoneDevice.CurrentEnvDeviceSelected(Package.EnvDte);
            if (devSelected != string.Empty)
            {
                if (UserSettings.Current.CloseXde)
                {
                    if (Package.PhoneDevice != null)
                    {
                        if (Package.PhoneDevice.Name != devSelected && Package.PhoneDevice.Connected)
                        {
                            Package.PhoneDevice.Disconnect();
                        }
                    }
                    var xdeprocess = Process.GetProcessesByName("XDE");
                    foreach (var process in xdeprocess.Where(process => process.MainWindowTitle != devSelected).ToArray())
                    {
                        process.CloseMainWindow();
                    }
                }
                if (Package.PhoneDevice != null && !Package.PhoneDevice.Connected)
                {
                    Package.PhoneDevice.SetCurrentConnectableDevice(devSelected);
                    CelPhoneManufature.Text = Package.PhoneDevice.Name;
                }
                LoadTreeViewDevice();
            }
        }

        internal void ResetBuild()
        {
            BuildProgressBar.Minimum = 0;
            BuildProgressBar.Maximum = 1;
            BuildProgressBar.Value = 0;
            BuildProgressBar.Visibility = Visibility.Hidden;
        }

        internal void UpdateMenu(bool allowedTools)
        {
            Menutransl.IsEnabled = allowedTools;
            ImgMenutransl.Source = allowedTools ?
                new BitmapImage(new Uri(Constants.RootResource + Constants.MenuIconTranslOn, UriKind.RelativeOrAbsolute))
                : new BitmapImage(new Uri(Constants.RootResource + Constants.MenuIconTranslOff, UriKind.RelativeOrAbsolute));
        }

        internal void StartSolutionBuild()
        {
            BuildProgressBar.Minimum = 0;
            BuildProgressBar.Maximum = 1;
            BuildProgressBar.Value = 0;
            BuildProgressBar.Visibility = Visibility.Visible;
            CelPhoneMsg.Text = AppRes.StartingBuild;
        }

        internal void EndSolutionBuild(string msg)
        {
            BuildProgressBar.Value = BuildProgressBar.Maximum;
            CelPhoneMsg.Text = msg;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    System.Threading.Thread.Sleep(1000);
                    ShowInfoEnvDevice();
                    ResetBuild();
                }));
        }

        internal void BuildSolutionStatus(string name, double currentPrj, int totPrj)
        {
            BuildProgressBar.Value = currentPrj / totPrj;
            CelPhoneMsg.Text = string.Format(AppRes.BuildingName, name);
        }

        internal void LoadTreeViewDevice()
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            TreeView.Items.Clear();
            if (Package.PhoneDevice == null || (Package.PhoneDevice != null && !Package.PhoneDevice.Connected))
            {
                InstalleddApp.Visibility = Visibility.Collapsed;
                Cursor = oldcur;
                return;
            }
            InstalleddApp.Visibility = Visibility.Visible;
            var apps = Package.PhoneDevice.ListApplicationsInstalled();
            //create treeview
            var root = new TreeViewWithIcons
            {
                HeaderText = CelPhoneManufature.Text,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.DeviceIcon,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsRootApp = true,
                CheckedVisibled = false
            };
            //root
            root.MouseRightButtonUp += DirectoryMouseRightButtonUp;
            root.PreviewMouseRightButtonDown += PreviewDirectoryMouseRightButtonDown;
            SubscribeFocusScrool(root);
            TreeView.Items.Add(root);

            // information device 
            var rootinfo = new TreeViewWithIcons
            {
                HeaderText = AppRes.DeviceInfo,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.Settings,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            };

            #region app core

            var appdev = Package.PhoneDevice.ListApplicationsCore();
            var rootdev = new TreeViewWithIcons
            {
                HeaderText = AppRes.AppCore,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.Settings,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            };
            foreach (var nodedev in appdev.Select(node => new TreeViewWithIcons
            {
                HeaderText = node.ProductName,
                Tag = node.ProductId,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.ExtDll,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                ToolTip = AppRes.ClickLaunch,
                CheckedVisibled = false
            }))
            {
                nodedev.MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
                rootdev.Items.Add(nodedev);
            }
            rootdev.MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
            rootinfo.Items.Add(rootdev);

            #endregion

            #region app settings

            var rootsett = new TreeViewWithIcons
            {
                HeaderText = AppRes.AppSett,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.Settings,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            };
            var appsett = Package.PhoneDevice.ListSettingsCore();
            foreach (var nodedev in appsett.Select(node => new TreeViewWithIcons
            {
                HeaderText = node.ProductName,
                Tag = node.ProductId,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.ExtDll,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                ToolTip = AppRes.ClickLaunch,
                CheckedVisibled = false
            }))
            {
                nodedev.MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
                rootsett.Items.Add(nodedev);
            }
            rootsett.MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
            rootinfo.Items.Add(rootsett);

            #endregion

            #region informations

            rootinfo.Items.Add(new TreeViewWithIcons
            {
                HeaderText = AppRes.Build + ": " + Package.PhoneDevice.OsBuildNo.ToString(CultureInfo.InvariantCulture),
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.FileDefault,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            });
            rootinfo.Items.Add(new TreeViewWithIcons
            {
                HeaderText = AppRes.Version + ": " + new Version(Package.PhoneDevice.OsMajor, Package.PhoneDevice.OsMinor),
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.FileDefault,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            });
            rootinfo.Items.Add(new TreeViewWithIcons
            {
                HeaderText = AppRes.Architecture + ": " + Package.PhoneDevice.ProcessorArchitecture + " " +
                                     Package.PhoneDevice.InstructionSet + " " +
                                     Package.PhoneDevice.NumberOfProcessors.ToString(CultureInfo.InvariantCulture) +
                                     AppRes.Processor,
                Tag = null,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.FileDefault,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsDevice = true,
                IsAppCore = true,
                IsRootApp = true,
                CheckedVisibled = false
            });
            rootinfo.MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
            foreach (var node in rootinfo.Items)
            {
                ((FrameworkElement)node).MouseLeftButtonUp += AppCoreMouseLeftButtonUp;
            }

            #endregion

            root.Items.Add(rootinfo);

            # region app installed

            foreach (var node in apps.Select(app => new TreeViewWithIcons
            {
                HeaderText = app.ProductName,
                Tag = app.ProductId,
                CheckedVisibled = false,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + Constants.ApplicationOffIcon,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsRootApp = true,
                ToolTip = AppRes.ClickRightApp,
                IsExpanded = false
            }))
            {
                node.Items.Add(new TreeViewWithIcons { Tag = "empty" });
                node.ToolTip = AppRes.EmptyRoot;
                SubscribeLoadExpanded(node);
                SubscribeFocusScrool(node);
                root.Items.Add(node);
            }

            #endregion

            root.IsExpanded = true;
            InstalledTitle.Text = AppRes.XInstalledApp + "(" + apps.Count + ").";
            Cursor = oldcur;
        }

        #endregion

        #region private methods

        private void UnSubscribeFocusScrool(TreeViewItem item)
        {
            item.Expanded -= NodeMouseLeftButtonUp;
            item.Collapsed -= NodeMouseLeftButtonUp;
            item.PreviewMouseLeftButtonUp -= NodeRootAppExpand;
        }

        private void SubscribeFocusScrool(TreeViewItem item)
        {
            item.Expanded += NodeMouseLeftButtonUp;
            item.Collapsed += NodeMouseLeftButtonUp;
            item.PreviewMouseLeftButtonUp += NodeRootAppExpand;
        }

        private void SubscribeLoadExpanded(TreeViewItem item)
        {
            item.MouseLeftButtonUp += NodeRootAppExpand;
            item.MouseRightButtonDown += NodeRootAppExpandRight;
            item.Expanded += AppNodeExpanded;
        }

        private void UnsubscribeLoadExpanded(TreeViewItem item)
        {
            item.MouseLeftButtonUp -= NodeRootAppExpand;
            item.MouseRightButtonDown -= NodeRootAppExpand;
            item.Expanded -= AppNodeExpanded;
        }

        private void RootNodeExpanded(TreeViewWithIcons rootAppnode, bool rightButtom)
        {
            if (rootAppnode.Items.Count == 0) return;

            UnsubscribeLoadExpanded(rootAppnode);
            var isfocus = true;
            if (((TreeViewWithIcons)rootAppnode.Items[0]).Tag != null)
            {
                if (rootAppnode.Items.Count == 1 && ((TreeViewWithIcons)rootAppnode.Items[0]).Tag.ToString() == "empty")
                {
                    LoadExpanded(rootAppnode);
                    if (rightButtom)
                    {
                        isfocus = false;
                        ShowDirMenu(rootAppnode);
                    }
                }
            }
            if (isfocus)
            {
                ScroolMain.Focus();
            }
        }

        private void AppNodeExpanded(object sender, RoutedEventArgs e)
        {
            RootNodeExpanded((TreeViewWithIcons)sender, false);
        }

        private void NodeRootAppExpandRight(object sender, MouseButtonEventArgs e)
        {
            RootNodeExpanded((TreeViewWithIcons)sender, true);
        }

        private void NodeRootAppExpand(object sender, MouseButtonEventArgs e)
        {
            RootNodeExpanded((TreeViewWithIcons)sender, false);
        }

        private static void PreviewDirectoryMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = (TreeViewItem)sender;
            item.Focus();
            item.IsSelected = true;
        }

        private void DirectoryMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            var item = (TreeViewWithIcons)sender;
            item.IsSelected = true;
            ShowDirMenu(item);
            e.Handled = true;
            Cursor = oldcur;
        }

        private void ShowDirMenu(TreeViewWithIcons item)
        {
            var contextMenu = new ContextMenu();
            MenuItem menuitem;
            IsoFilesView isofile;

            if (item.IsDevice && item.IsRootApp)
            {
                menuitem = new MenuItem { Header = AppRes.RefreshDevice, Tag = "RefreshDev", Icon = MainUserControl.Resources["ImgRefresh"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);
                item.ContextMenu = contextMenu;
                contextMenu.IsOpen = true;
                return;
            }

            string id;
            if (item.IsRootApp)
            {
                id = item.Tag.ToString();
                isofile = _isoFiles[id];
            }
            else
            {
                var tmp = item.Tag.ToString().Split('|');
                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                id = tmp[0];
            }

            if (isofile.IsRoot)
            {
                if (item.IsRootApp)
                {
                    var ok = false;
                    var cache = WpIsolateSaveData.Current.WpApplication.FirstOrDefault(a => a.Guid == id);
                    if (cache == null)
                    {
                        if (item.HeaderText == id)
                        {
                            ok = true;
                        }
                    }
                    else
                    {
                        if (cache.Guid == cache.Title)
                        {
                            ok = true;
                        }
                    }
                    if (ok)
                    {
                        menuitem = new MenuItem { Header = AppRes.NewAlias, Tag = "AliasApp", Icon = MainUserControl.Resources["ImgRename"] };
                        menuitem.Click += DirMenuClick;
                        contextMenu.Items.Add(menuitem);
                    }
                }

                menuitem = new MenuItem { Header = AppRes.Refresh, Tag = "RefreshApp", Icon = MainUserControl.Resources["ImgRefresh"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);

                contextMenu.Items.Add(new Separator());

                menuitem = new MenuItem { Header = AppRes.Run, Tag = "RunApp", Icon = MainUserControl.Resources["ImgRun"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);

                menuitem = new MenuItem { Header = AppRes.Uninstall, Tag = "UninstallApp", Icon = MainUserControl.Resources["ImgDelete"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);

                contextMenu.Items.Add(new Separator());
            }

            var qtdfiles = CountFiles(isofile, true);
            if (qtdfiles > 0)
            {
                menuitem = new MenuItem { Header = AppRes.CopyFolderAndFiles, Tag = "CopyDir", Icon = MainUserControl.Resources["ImgCopy"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);
            }

            if (!isofile.IsRoot && !isofile.IsSystem)
            {
                menuitem = new MenuItem { Header = AppRes.DeleteFolder, Tag = "DeleteDir", Icon = MainUserControl.Resources["ImgDelete"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);
            }

            menuitem = new MenuItem { Header = AppRes.CreateFolder, Tag = "CreateFolder", Icon = MainUserControl.Resources["ImgNewDir"] };
            menuitem.Click += DirMenuClick;
            contextMenu.Items.Add(menuitem);

            contextMenu.Items.Add(new Separator());

            menuitem = new MenuItem { Header = AppRes.AddFiles, Tag = "AddFilesDir", Icon = MainUserControl.Resources["ImgAdd"] };
            menuitem.Click += DirMenuClick;
            contextMenu.Items.Add(menuitem);

            var qtdfilesinfolder = CountFiles(isofile, false);
            if (qtdfilesinfolder > 0)
            {
                menuitem = new MenuItem { Header = AppRes.DeleteFilesFolder, Tag = "DeleteFilesDir", Icon = MainUserControl.Resources["ImgDeleteFiles"] };
                menuitem.Click += DirMenuClick;
                contextMenu.Items.Add(menuitem);

            }
            item.ContextMenu = contextMenu;
            contextMenu.IsOpen = true;
        }

        private static bool ExistCheck(IsoFilesView item, bool recursive)
        {
            if (item.Files == null)
            {
                return false;
            }
            foreach (var file in item.Files)
            {
                if (file.IsDiretory || file.IsRoot)
                {
                    if (recursive)
                    {
                        if (ExistCheck(file, true))
                        {
                            return true;
                        }
                    }
                }
                else
                {
                    if (!file.IsSystem && file.Seleted)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private static int CountFiles(IsoFilesView item, bool recursive)
        {
            var qtd = 0;
            if (item.Files == null)
            {
                return 0;
            }
            foreach (var file in item.Files)
            {
                if (file.IsDiretory || file.IsRoot)
                {
                    if (recursive)
                    {
                        qtd += CountFiles(file, true);
                    }
                }
                else
                {
                    if (!file.IsSystem)
                    {
                        qtd++;
                    }
                }
            }
            return qtd;
        }

        private void DirMenuClick(object sender, RoutedEventArgs e)
        {
            var ids = string.Empty;
            if (((FrameworkElement)TreeView.SelectedItem).Tag != null)
            {
                ids = ((FrameworkElement)TreeView.SelectedItem).Tag.ToString();
            }
            var command = ((FrameworkElement)sender).Tag.ToString();

            CelPhoneMsg.Text = AppRes.WaitCommand;
            //IsEnabled = false;

            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() => CommmandMenuExplorer(command, ids, (TreeViewWithIcons)TreeView.SelectedItem)));
        }

        private void CommmandMenuExplorer(string command, string ids, TreeViewWithIcons node)
        {
            switch (command)
            {
                case "AliasApp":
                    #region  AliasApp

                    {
                        string id;
                        if (node.IsRootApp)
                        {
                            id = ids;
                        }
                        else
                        {
                            var tmp = ids.Split('|');
                            id = tmp[0];
                        }
                        var cache = WpIsolateSaveData.Current.WpApplication.FirstOrDefault(a => a.Guid == id);
                        var newname = string.Empty;
                        if (cache != null)
                        {
                            newname = cache.RenameTitle;
                        }
                        var result = InputBoxControl.InputBox(AppRes.ToolWindowTitle, AppRes.NewAlias, ref newname);
                        if (result == DialogResult.OK)
                        {
                            if (string.IsNullOrEmpty(newname))
                            {
                                MessageBox.Show(AppRes.NewNameEmpty, AppRes.ToolWindowTitle);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            if (!Package.PhoneDevice.Connect())
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            try
                            {
                                if (cache != null)
                                {
                                    cache.RenameTitle = newname;
                                }
                                else
                                {
                                    cache = new WpDeployApplication { Guid = id, Title = node.HeaderText, RenameTitle = newname };
                                }
                                WpIsolateSaveData.Current.AddData(cache);
                                node.HeaderText = newname;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "RefreshDev":
                    #region RefreshDev

                    {
                        if (Package.PhoneDevice.Connected)
                        {
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsEnabled = false;
                            try
                            {
                                LoadTreeViewDevice();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                            }
                            IsEnabled = true;
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "RefreshApp":
                    #region RefreshApp

                    {
                        if (Package.PhoneDevice.Connected)
                        {
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            try
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                LoadExpanded(node);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "RunApp":
                    #region RunApp

                    {
                        if (Package.PhoneDevice.Connected)
                        {
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            try
                            {
                                var id = ids.Split('|')[0];
                                var existingInstall = Package.PhoneDevice.GetApplication(id);
                                if (existingInstall != null)
                                {
                                    Package.PhoneDevice.TerminateRunningInstances(id);
                                    Package.PhoneDevice.Launch(id);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "UninstallApp":
                    #region UninstallApp

                    {
                        if (Package.PhoneDevice.Connected)
                        {
                            var result = MessageBox.Show(string.Format(AppRes.QUinstall, node.HeaderText), AppRes.ToolWindowTitle,
                                                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (!Package.PhoneDevice.Connected)
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    CelPhoneMsg.Text = Package.StatusConnect;
                                    IsEnabled = true;
                                    return;
                                }
                                var oldcur = Cursor;
                                Cursor = Cursors.Wait;
                                try
                                {
                                    var id = ids.Split('|')[0];
                                    var existingInstall = Package.PhoneDevice.GetApplication(id);
                                    if (existingInstall != null)
                                    {
                                        Package.PhoneDevice.TerminateRunningInstances(id);
                                        Package.PhoneDevice.Uninstall(id);
                                    }
                                    ((TreeViewItem)node.Parent).Items.Remove(node);
                                    InstalledTitle.Text = AppRes.XInstalledApp + "(" + Package.PhoneDevice.ListApplicationsInstalled().Count + ").";
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                                }
                                Cursor = oldcur;
                            }
                        }
                    }

                    #endregion
                    break;
                case "CopyFilesSeleted":
                case "CopyDir":
                    #region CopyDir

                    {
                        var folderDialog = new FolderBrowserDialog { Description = AppRes.DescFolderCopy };

                        if (folderDialog.ShowDialog() == DialogResult.OK)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var desktopfolder = folderDialog.SelectedPath;
                            var deskDirinfo = new DirectoryInfo(desktopfolder);
                            if (deskDirinfo.Root.FullName == deskDirinfo.FullName)
                            {
                                MessageBox.Show(AppRes.ErrRootDel, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var desktopapp = Path.Combine(desktopfolder, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText);
                            if (Directory.Exists(desktopapp))
                            {
                                var result = MessageBox.Show(string.Format(AppRes.QDelDir, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText), AppRes.ToolWindowTitle,
                                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.No)
                                {
                                    CelPhoneMsg.Text = Package.StatusConnect;
                                    IsEnabled = true;
                                    return;
                                }
                            }
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile = null;
                            string id = null;
                            if (node != null)
                            {
                                if (node.IsRootApp)
                                {
                                    isofile = _isoFiles[ids];
                                    id = ids;
                                }
                                else
                                {
                                    var tmp = ids.Split('|');
                                    isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                    id = tmp[0];
                                }
                            }
                            try
                            {
                                var qtddir = 0;
                                var qtdfiles = 0;
                                if (!Directory.Exists(desktopfolder))
                                {
                                    Directory.CreateDirectory(desktopfolder);
                                }
                                desktopfolder = Path.Combine(desktopfolder, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText);
                                if (Directory.Exists(desktopfolder))
                                {
                                    Directory.Delete(desktopfolder, true);
                                }
                                desktopfolder = Directory.CreateDirectory(desktopfolder).FullName;

                                var filesnotcopy = new List<string>();
                                if (node != null)
                                {
                                    var appdesktopfolder = !node.IsRootApp ? FindRootApp(node).HeaderText : node.HeaderText;
                                    appdesktopfolder = Path.Combine(desktopfolder, appdesktopfolder);
                                    Directory.CreateDirectory(appdesktopfolder);
                                    filesnotcopy.AddRange(Package.PhoneDevice.CopyIsoDir(id, isofile, appdesktopfolder, false, ref qtddir, ref qtdfiles));
                                }
                                else
                                {
                                    foreach (var app in ((TreeViewItem)TreeView.Items[0]).Items.Cast<TreeViewWithIcons>().Where(app => !app.IsDevice && app.IsRootApp).Where(app => _isoFiles.ContainsKey(app.Tag.ToString())))
                                    {
                                        isofile = _isoFiles[app.Tag.ToString()];
                                        var hascheck = ExistCheck(isofile, true);
                                        if (hascheck)
                                        {
                                            var appdesktopfolder = Path.Combine(desktopfolder, app.HeaderText);
                                            Directory.CreateDirectory(appdesktopfolder);
                                            filesnotcopy.AddRange(Package.PhoneDevice.CopyIsoDir(app.Tag.ToString(), isofile, appdesktopfolder, true, ref qtddir, ref qtdfiles));
                                        }
                                    }
                                }

                                var msg = AppRes.FolderCop + qtddir.ToString(CultureInfo.InvariantCulture) + "\n";
                                msg += AppRes.FileCop + qtdfiles.ToString(CultureInfo.InvariantCulture) + "\n";
                                var msgerr = filesnotcopy.Aggregate(string.Empty, (current, s) => current + (s + "\n"));
                                if (msgerr.Length != 0)
                                {
                                    Cursor = oldcur;
                                    msg += "\n" + AppRes.Errors + "\n" + msgerr;
                                    MessageBox.Show(msg, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                                else
                                {
                                    Process.Start("explorer.exe", desktopfolder);
                                }
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "DeleteDir":
                    #region DeleteDir

                    {
                        var result = MessageBox.Show(AppRes.QDelFolder, AppRes.ToolWindowTitle,
                                                     MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            try
                            {
                                Package.PhoneDevice.DeleteIsoDir(id, isofile);
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            if (Package.PhoneDevice.Connected)
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                var rnode = FindRootApp(node);
                                LoadExpanded(rnode);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "CreateFolder":
                    #region CreateFolder

                    {
                        var newforder = string.Empty;
                        var result = InputBoxControl.InputBox(AppRes.ToolWindowTitle, AppRes.FolderName, ref newforder);
                        if (result == DialogResult.OK)
                        {
                            if (string.IsNullOrEmpty(newforder))
                            {
                                MessageBox.Show(AppRes.FoderNameEmpty, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            try
                            {
                                Package.PhoneDevice.CreateIsoDir(id, isofile, newforder);
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            if (Package.PhoneDevice.Connected)
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                var rnode = FindRootApp(node);
                                LoadExpanded(rnode);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "AddFilesDir":
                    #region AddFilesDir

                    {
                        var openfiles = new OpenFileDialog { Multiselect = true, Title = AppRes.ToolWindowTitle };
                        if (openfiles.ShowDialog() == true)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            var errors = string.Empty;
                            var qtdfiles = 0;
                            try
                            {
                                foreach (var err in openfiles.FileNames.Select(file => Package.PhoneDevice.CopySendFile(id, isofile, file, true)))
                                {
                                    if (err.Length == 0)
                                    {
                                        qtdfiles++;
                                    }
                                    else
                                    {
                                        errors += err + "\n";
                                    }
                                }
                                if (errors.Length != 0)
                                {
                                    Cursor = oldcur;
                                    var msg = AppRes.FileCop + qtdfiles.ToString(CultureInfo.InvariantCulture) + AppRes.Errors + "\n" + errors;
                                    MessageBox.Show(msg, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            if (Package.PhoneDevice.Connected)
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                var rnode = FindRootApp(node);
                                LoadExpanded(rnode);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "DeleteFilesDir":
                    #region DeleteFilesDir

                    {
                        var result = MessageBox.Show(AppRes.QDelAllFiles, AppRes.ToolWindowTitle,
                                                     MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            var errors = string.Empty;
                            var qtdfiles = 0;
                            try
                            {
                                foreach (var err in from item in isofile.Files where !item.IsDiretory && !item.IsRoot && !item.IsSystem select Package.PhoneDevice.DeleteFile(id, isofile, item.Name))
                                {
                                    if (err.Length == 0)
                                    {
                                        qtdfiles++;
                                    }
                                    else
                                    {
                                        errors += err + "\n";
                                    }
                                }
                                if (errors.Length != 0)
                                {
                                    Cursor = oldcur;
                                    var msg = AppRes.FilesDel + qtdfiles.ToString(CultureInfo.InvariantCulture) + AppRes.Errors + "\n" + errors;
                                    MessageBox.Show(msg, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            if (Package.PhoneDevice.Connected)
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                var rnode = FindRootApp(node);
                                LoadExpanded(rnode);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "DeleteFilesSeleted":
                    #region DeleteFilesSeleted

                    {
                        var result = MessageBox.Show(AppRes.QDelSeleted, AppRes.ToolWindowTitle,
                                                     MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            var qtdfiles = 0;
                            try
                            {

                                var filesnotdel = new List<string>();
                                foreach (var app in ((TreeViewItem)TreeView.Items[0]).Items.Cast<TreeViewWithIcons>().Where(app => !app.IsDevice && app.IsRootApp).Where(app => _isoFiles.ContainsKey(app.Tag.ToString())))
                                {
                                    var isofile = _isoFiles[app.Tag.ToString()];
                                    var hascheck = ExistCheck(isofile, true);
                                    if (hascheck)
                                    {
                                        filesnotdel.AddRange(Package.PhoneDevice.DeleteSelectedIsoDir(app.Tag.ToString(), isofile.Files, ref qtdfiles));
                                        app.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                        app.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                        UnSubscribeFocusScrool(app);
                                        LoadExpanded(app);
                                    }
                                }
                                var msg = AppRes.FilesDel + qtdfiles.ToString(CultureInfo.InvariantCulture);
                                var msgerr = filesnotdel.Aggregate(string.Empty, (current, s) => current + (s + "\n"));
                                if (msgerr.Length != 0)
                                {
                                    Cursor = oldcur;
                                    msg += "\n" + AppRes.Errors + "\n" + msgerr;
                                    MessageBox.Show(msg, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                                else
                                {
                                    ActCopysel.IsEnabled = false;
                                    ActDeletesel.IsEnabled = false;
                                    ActCopysel.Foreground = VsTheming.GetWindowDisabledText();
                                    ActDeletesel.Foreground = VsTheming.GetWindowDisabledText();
                                }
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "CopyFile":
                    #region CopyFile

                    {
                        string desktopfolder;
                        var folderDialog = new FolderBrowserDialog { Description = AppRes.DescFolderCopy };
                        if (folderDialog.ShowDialog() == DialogResult.OK)
                        {
                            desktopfolder = folderDialog.SelectedPath;
                            var desktopapp = Path.Combine(desktopfolder, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText);
                            if (Directory.Exists(desktopapp))
                            {
                                var result = MessageBox.Show(string.Format(AppRes.QDelDir, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText), AppRes.ToolWindowTitle,
                                        MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.No)
                                {
                                    CelPhoneMsg.Text = Package.StatusConnect;
                                    IsEnabled = true;
                                    return;
                                }
                            }
                        }
                        else
                        {
                            CelPhoneMsg.Text = Package.StatusConnect;
                            IsEnabled = true;
                            return;
                        }
                        if (!Package.PhoneDevice.Connected)
                        {
                            MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                            CelPhoneMsg.Text = Package.StatusConnect;
                            IsEnabled = true;
                            return;
                        }
                        var oldcur = Cursor;
                        Cursor = Cursors.Wait;
                        IsoFilesView isofile;
                        string id;
                        if (node.IsRootApp)
                        {
                            isofile = _isoFiles[ids];
                            id = ids;
                        }
                        else
                        {
                            var tmp = ids.Split('|');
                            isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                            id = tmp[0];
                        }

                        try
                        {
                            if (!Directory.Exists(desktopfolder))
                            {
                                Directory.CreateDirectory(desktopfolder);
                            }

                            desktopfolder = Path.Combine(desktopfolder, ((TreeViewWithIcons)TreeView.Items[0]).HeaderText);
                            if (Directory.Exists(desktopfolder))
                            {
                                Directory.Delete(desktopfolder, true);
                            }
                            desktopfolder = Directory.CreateDirectory(desktopfolder).FullName;


                            var appdesktopfolder = !node.IsRootApp ? FindRootApp(node).HeaderText : node.HeaderText;
                            appdesktopfolder = Path.Combine(desktopfolder, appdesktopfolder);
                            Directory.CreateDirectory(appdesktopfolder);

                            desktopfolder = Package.PhoneDevice.CopyReceiveFile(id, isofile, appdesktopfolder);
                            Process.Start("explorer.exe", desktopfolder);
                        }
                        catch (Exception ex)
                        {
                            Cursor = oldcur;
                            MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        Cursor = oldcur;
                    }

                    #endregion
                    break;
                case "DeleteFile":
                    #region DeleteFile

                    {
                        var result = MessageBox.Show(AppRes.QDelFile, AppRes.ToolWindowTitle,
                             MessageBoxButton.YesNo, MessageBoxImage.Question);

                        if (result == MessageBoxResult.Yes)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            try
                            {
                                Package.PhoneDevice.DeleteFile(id, isofile, string.Empty);
                                ((TreeViewItem)node.Parent).Items.Remove(node);
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "RenameFile":
                    #region RenameFile

                    {
                        var newfile = string.Empty;
                        var result = InputBoxControl.InputBox(AppRes.ToolWindowTitle, AppRes.NewName, ref newfile);
                        if (result == DialogResult.OK)
                        {
                            if (!Package.PhoneDevice.Connected)
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            if (string.IsNullOrEmpty(newfile))
                            {
                                MessageBox.Show(AppRes.NewNameEmpty, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                                CelPhoneMsg.Text = Package.StatusConnect;
                                IsEnabled = true;
                                return;
                            }
                            var oldcur = Cursor;
                            Cursor = Cursors.Wait;
                            IsoFilesView isofile;
                            string id;
                            if (node.IsRootApp)
                            {
                                isofile = _isoFiles[ids];
                                id = ids;
                            }
                            else
                            {
                                var tmp = ids.Split('|');
                                isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                                id = tmp[0];
                            }
                            try
                            {
                                Package.PhoneDevice.RenameFile(id, isofile, newfile);
                            }
                            catch (Exception ex)
                            {
                                Cursor = oldcur;
                                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            if (Package.PhoneDevice.Connected)
                            {
                                node.MouseRightButtonUp -= DirectoryMouseRightButtonUp;
                                node.PreviewMouseRightButtonDown -= PreviewDirectoryMouseRightButtonDown;
                                UnSubscribeFocusScrool(node);
                                var rnode = FindRootApp(node);
                                LoadExpanded(rnode);
                            }
                            Cursor = oldcur;
                        }
                    }

                    #endregion
                    break;
                case "InspectAppSettings":
                    #region InspectAppSettings
                    {
                        if (!Package.PhoneDevice.Connected)
                        {
                            MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                            CelPhoneMsg.Text = Package.StatusConnect;
                            IsEnabled = true;
                            return;
                        }
                        var oldcur = Cursor;
                        Cursor = Cursors.Wait;
                        IsoFilesView isofile;
                        string id;
                        if (node.IsRootApp)
                        {
                            isofile = _isoFiles[ids];
                            id = ids;
                        }
                        else
                        {
                            var tmp = ids.Split('|');
                            isofile = FindisoFile(_isoFiles[tmp[0]], tmp[1]);
                            id = tmp[0];
                        }

                        try
                        {
                            var desktopfolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), ((TreeViewWithIcons)TreeView.Items[0]).HeaderText);
                            if (Directory.Exists(desktopfolder))
                            {
                                Directory.Delete(desktopfolder, true);
                            }
                            desktopfolder = Directory.CreateDirectory(desktopfolder).FullName;

                            var rootnode = !node.IsRootApp ? FindRootApp(node).HeaderText : node.HeaderText;
                            var appdesktopfolder = Path.Combine(desktopfolder, rootnode);
                            Directory.CreateDirectory(appdesktopfolder);
                            desktopfolder = Package.PhoneDevice.CopyReceiveFile(id, isofile, appdesktopfolder);
                            var fname = desktopfolder + "\\" + isofile.Name;
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string, string>(ShowInspectDialog), rootnode, fname);
                        }
                        catch (Exception ex)
                        {
                            Cursor = oldcur;
                            MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        Cursor = oldcur;
                    }
                    #endregion
                    break;
            }
            CelPhoneMsg.Text = Package.StatusConnect;
            IsEnabled = true;
        }

        private void ShowInspectDialog(string root, string fname)
        {
            var dic = InspectorDataContractSerializer.Read(fname);
            var dialog = new InspectAppSettingsDialog { Settings = dic, RootNode = root };
            dialog.ShowModal();
        }
        private static IsoFilesView FindisoFile(IsoFilesView isof, string id)
        {
            IsoFilesView result = null;
            if (isof.Id == id)
            {
                return isof;
            }
            if (isof.Files != null)
            {
                foreach (var item in isof.Files)
                {
                    if (item.Id == id)
                    {
                        result = item;
                        break;
                    }
                    if (item.Files != null)
                    {
                        result = FindisoFile(item, id);
                        if (result != null)
                        {
                            break;
                        }
                    }
                }
            }
            return result;
        }

        private void ActselectMouseEnter(object sender, MouseEventArgs e)
        {
            ((TextBlock)sender).Foreground = VsTheming.GetWindowHighlightText();
        }

        private void ActselectMouseLeave(object sender, MouseEventArgs e)
        {
            ((TextBlock)sender).Foreground = VsTheming.GetWindowText();
        }

        private void ActCopyselMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            CommmandMenuExplorer("CopyFilesSeleted", null, null);
        }

        private void ActDeleteselMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            CommmandMenuExplorer("DeleteFilesSeleted", null, null);
        }

        private ConnectableDevice ChangeDevice(bool next)
        {
            var avaliableDevices = Package.PhoneDevice.Devices.ToArray();
            for (var i = 0; i < avaliableDevices.Count(); i++)
            {
                if (avaliableDevices[i].Name.ToUpper() == CelPhoneManufature.Text.ToUpper())
                {
                    if (next)
                    {
                        return i == avaliableDevices.Count() - 1 ? avaliableDevices[0] : avaliableDevices[i + 1];
                    }
                    return i == 0 ? avaliableDevices[avaliableDevices.Count() - 1] : avaliableDevices[i - 1];
                }
            }
            return null;
        }

        //private void EnvPhoneDeviceChangedTargetDevice(object sender, EventArgs e)
        //{
        //    if (!Package.PhoneDevice.Connected || Package.DbgmodeNew != DBGMODE.DBGMODE_Design)
        //    {
        //        Dispatcher.BeginInvoke(DispatcherPriority.Background,
        //            new Action(() =>
        //            {
        //                CelPhoneManufature.Text = EnvPhoneDevice.CurrentTargetDevice;
        //                CelPhoneVersion.Text = EnvPhoneDevice.PhoneVersion;
        //            }));
        //    }
        //}

        private void TimerTick(object sender, EventArgs e)
        {
            if (!Package.PhoneDevice.Connected)
            {
                CelPhoneMsg.Text = AppRes.WaitDisconnecting;
                BntDisconnect.IsEnabled = false;
                TryDisconnectCallBack();
                CelPhoneManufature.Text = EnvPhoneDevice.CurrentEnvDeviceSelected(Package.EnvDte);
                Timer.Stop();
            }
        }

        private void BntConnectClick(object sender, RoutedEventArgs e)
        {
            ConnectDevice();
        }

        internal void ConnectDevice()
        {
            CelPhoneMsg.Text = AppRes.WaitConnecting;
            BntConnect.IsEnabled = false;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(TryconnectCallBack));
        }


        private void TryconnectCallBack()
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            CelPhoneMsgErro.Text = string.Empty;
            CelPhoneMsgErro.Visibility = Visibility.Collapsed;

            if (!Package.PhoneDevice.Connect())
            {
                CelPhoneMsgErro.Visibility = Visibility.Visible;
                if (Package.PhoneDevice.ErrorMessage != null)
                {
                    CelPhoneMsgErro.Text = Package.PhoneDevice.ErrorMessage;
                }
            }
            LoadTreeViewDevice();
            ShowInfoEnvDevice();
            ChangeBntConnect();
            BntConnect.IsEnabled = true;
            if (Package.PhoneDevice.Connected)
            {
                DeviceLeft.Visibility = Visibility.Collapsed;
                Timer.Start();
            }
            else
            {
                DeviceLeft.Visibility = Visibility.Visible;
                Timer.Stop();
            }
            Cursor = oldcur;
        }

        private void AppCoreMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var item = (TreeViewWithIcons)sender;
            item.IsSelected = false;
            if (item.IsRootApp)
            {
                return;
            }
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<string>(LaunchApp), item.Tag.ToString());
        }

        private void LaunchApp(object arg)
        {
            try
            {
                var oldcur = Cursor;
                Cursor = Cursors.Wait;
                Package.PhoneDevice.Launch(arg.ToString());
                Cursor = oldcur;
            }
            catch (Exception ex)
            {
                MessageBox.Show(AppRes.LaunchError + ex.Message, AppRes.ToolWindowTitle);
            }
        }

        private TreeViewWithIcons FindRootApp(TreeViewWithIcons node)
        {
            while (!node.IsRootApp)
            {
                node = (TreeViewWithIcons)node.Parent;
            }
            return node;
        }

        private void LoadExpanded(TreeViewWithIcons rootAppnode)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            rootAppnode.Items.Clear();
            rootAppnode.Icon = new BitmapImage(
                new Uri(Constants.RootResource + Constants.ApplicationOnIcon,
                        UriKind.RelativeOrAbsolute));

            var id = rootAppnode.Tag.ToString().Split('|')[0];
            if (!_isoFiles.ContainsKey(id))
            {
                _isoFiles.Add(id, null);
            }
            _isoFiles[id] = Package.PhoneDevice.GetIsoFiles(id);
            //create Strutuct
            if (_isoFiles[id].Files != null)
            {
                foreach (var isoFilesView in _isoFiles[id].Files)
                {
                    if (isoFilesView.IsDiretory)
                    {
                        AddDirectory(rootAppnode, isoFilesView);
                    }
                    else
                    {
                        AddFile(rootAppnode, isoFilesView);
                    }
                }
                rootAppnode.ToolTip = AppRes.ClickRightApp;
                rootAppnode.ExpandSubtree();
                rootAppnode.MouseRightButtonUp += DirectoryMouseRightButtonUp;
                rootAppnode.PreviewMouseRightButtonDown += PreviewDirectoryMouseRightButtonDown;
                SubscribeFocusScrool(rootAppnode);
            }
            Cursor = oldcur;
        }

        private void AddDirectory(ItemsControl root, IsoFilesView item)
        {
            item.Icon = Common.GetIcon(item);
            var node = new TreeViewWithIcons
            {
                HeaderText = item.Name,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + item.Icon,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsAppUser = true,
                Tag = item.IdApp + "|" + item.Id
            };
            if (item.Files != null)
            {
                foreach (var child in item.Files)
                {
                    if (child.IsDiretory)
                    {
                        AddDirectory(node, child);
                    }
                    else
                    {
                        AddFile(node, child);
                    }
                }
            }
            root.Items.Add(node);
            node.MouseRightButtonUp += DirectoryMouseRightButtonUp;
            node.PreviewMouseRightButtonDown += PreviewDirectoryMouseRightButtonDown;
            node.ChangeCheckItem += TreeChangeCheckItem;
            node.Expanded += RootOnExpanded;
            node.Collapsed += RootOnCollapsed;
            SubscribeFocusScrool(node);
        }

        private void NodeMouseLeftButtonUp(object sender, RoutedEventArgs e)
        {
            ScroolMain.Focus();
        }

        private static void RootOnCollapsed(object sender, RoutedEventArgs e)
        {
            var item = (TreeViewWithIcons)sender;
            if (item.Items.Count > 0)
            {
                item.Icon =
                new BitmapImage(
                    new Uri(Constants.RootResource + Constants.FolderClose,
                            UriKind.RelativeOrAbsolute));
            }
            e.Handled = true;
        }

        private static void RootOnExpanded(object sender, RoutedEventArgs e)
        {
            var item = (TreeViewWithIcons)sender;
            if (item.Items.Count > 0)
            {
                item.Icon =
                    new BitmapImage(
                        new Uri(Constants.RootResource + Constants.FolderOpen,
                                UriKind.RelativeOrAbsolute));
            }
            else
            {
                item.Icon =
                    new BitmapImage(
                        new Uri(Constants.RootResource + Constants.FolderClose,
                                UriKind.RelativeOrAbsolute));
            }
            e.Handled = true;
        }

        private void TreeChangeCheckItem(object sender, RoutedEventArgs e)
        {
            var tmp = ((TreeViewCheckClickEvent)e).TreeItem;
            SetIsChecked(tmp, true, true);
            var mark = ((TreeViewWithIcons)TreeView.Items[0]).Checked;
            if (!mark.HasValue)
            {
                ActCopysel.IsEnabled = true;
                ActDeletesel.IsEnabled = true;
            }
            else
            {
                ActCopysel.IsEnabled = mark.Value;
                ActDeletesel.IsEnabled = mark.Value;
            }
            if (ActCopysel.IsEnabled || ActDeletesel.IsEnabled)
            {
                ActCopysel.Foreground = VsTheming.GetWindowText();
                ActDeletesel.Foreground = VsTheming.GetWindowText();
            }
            else
            {
                ActCopysel.Foreground = VsTheming.GetWindowDisabledText();
                ActDeletesel.Foreground = VsTheming.GetWindowDisabledText();
            }
            ScroolMain.Focus();
        }

        private void SetIsChecked(TreeViewWithIcons item, bool updateChildren, bool updateParent)
        {
            if (updateChildren)
            {
                item.Checked = item.Checked.HasValue && item.Checked.Value;

                if (item.IsRootApp)
                {
                    CheckedisoFile(_isoFiles[item.Tag.ToString()], item.Tag.ToString(), item.Checked.Value);
                }
                else
                {
                    var id = item.Tag.ToString().Split('|');
                    CheckedisoFile(_isoFiles[id[0]], id[1], item.Checked.Value);
                }

                foreach (TreeViewWithIcons subitem in item.Items)
                {
                    subitem.Checked = item.Checked.Value;
                    if (subitem.IsRootApp)
                    {
                        CheckedisoFile(_isoFiles[subitem.Tag.ToString()], subitem.Tag.ToString(), subitem.Checked.Value);
                    }
                    else
                    {
                        var id = subitem.Tag.ToString().Split('|');
                        CheckedisoFile(_isoFiles[id[0]], id[1], subitem.Checked.Value);
                    }

                    if (subitem.Items.Count > 0)
                    {
                        SetIsChecked(subitem, true, false);
                    }
                }
            }
            if (updateParent && item.Parent != null)
            {
                var treeViewWithIcons = item.Parent as TreeViewWithIcons;
                if (treeViewWithIcons != null)
                {
                    VerifyCheckState(treeViewWithIcons);
                }
            }
        }

        private void VerifyCheckState(TreeViewWithIcons item)
        {
            bool? state = null;
            for (var i = 0; i < item.Items.Count; ++i)
            {
                var current = ((TreeViewWithIcons)item.Items[i]).Checked;
                if (i == 0)
                {
                    state = current;
                }
                else if (state != current)
                {
                    state = null;
                    break;
                }
            }
            item.Checked = state;
            if (item.Tag == null)
            {
                return;
            }
            if (!item.Checked.HasValue || (item.Checked.Value))
            {
                if (item.IsRootApp)
                {
                    CheckedisoFile(_isoFiles[item.Tag.ToString()], item.Tag.ToString(), true);
                }
                else
                {
                    var id = item.Tag.ToString().Split('|');
                    CheckedisoFile(_isoFiles[id[0]], id[1], true);
                }
            }
            else
            {
                if (item.IsRootApp)
                {
                    CheckedisoFile(_isoFiles[item.Tag.ToString()], item.Tag.ToString(), false);
                }
                else
                {
                    var id = item.Tag.ToString().Split('|');
                    CheckedisoFile(_isoFiles[id[0]], id[1], false);
                }
            }
            if (item.Parent != null)
            {
                var treeViewWithIcons = item.Parent as TreeViewWithIcons;
                if (treeViewWithIcons != null)
                {
                    VerifyCheckState(treeViewWithIcons);
                }
            }
        }

        private static IsoFilesView CheckedisoFile(IsoFilesView isof, string id, bool value)
        {
            IsoFilesView result = null;
            if (isof.Id == id)
            {
                isof.Seleted = value;
                return isof;
            }
            if (isof.Files != null)
            {
                foreach (var item in isof.Files)
                {
                    if (item.Id == id)
                    {
                        item.Seleted = value;
                        break;
                    }
                    if (item.Files != null)
                    {
                        result = CheckedisoFile(item, id, value);
                        if (result != null)
                        {
                            break;
                        }
                    }
                }
            }
            return result;
        }

        private void AddFile(ItemsControl root, IsoFilesView item)
        {
            item.Icon = Common.GetIcon(item);
            var node = new TreeViewWithIcons
            {
                HeaderText = item.Name,
                Icon =
                    new BitmapImage(
                    new Uri(Constants.RootResource + item.Icon,
                            UriKind.RelativeOrAbsolute)),
                IconHeight = 16,
                IconWidth = 16,
                IsAppUser = true,
                Tag = item.IdApp + "|" + item.Id
            };
            var tooptip = AppRes.FileTitle + item.Name + "\n" +
                          AppRes.Size + Common.FormatBytes(item.Length);
            node.ToolTip = tooptip;
            node.MouseRightButtonUp += FileMouseRightButtonUp;
            node.MouseRightButtonDown += PreviewFileMouseRightButtonDown;
            node.ChangeCheckItem += TreeChangeCheckItem;
            SubscribeFocusScrool(node);
            root.Items.Add(node);
        }

        private void FileMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            var item = (TreeViewItem)sender;
            item.IsSelected = true;
            ShowFileMenu(item);
            e.Handled = true;
            Cursor = oldcur;
        }

        private void ShowFileMenu(FrameworkElement item)
        {

            var id = item.Tag.ToString().Split('|');
            var isofile = FindisoFile(_isoFiles[id[0]], id[1]);

            var contextMenu = new ContextMenu();
            MenuItem menuitem;

            if (isofile.Name == "__ApplicationSettings")
            {
                menuitem = new MenuItem { Header = AppRes.InspectAppSettings, Tag = "InspectAppSettings", Icon = MainUserControl.Resources["ImgLupa"] };
                menuitem.Click += FileMenuClick;
                contextMenu.Items.Add(menuitem);
            }

            menuitem = new MenuItem { Header = AppRes.CopyFile, Tag = "CopyFile", Icon = MainUserControl.Resources["ImgCopy"] };
            menuitem.Click += FileMenuClick;
            contextMenu.Items.Add(menuitem);

            if (!isofile.IsSystem)
            {
                menuitem = new MenuItem { Header = AppRes.DeleteFile, Tag = "DeleteFile", Icon = MainUserControl.Resources["ImgDelete"] };
                menuitem.Click += FileMenuClick;
                contextMenu.Items.Add(menuitem);
            }
            if (!isofile.IsSystem)
            {
                menuitem = new MenuItem { Header = AppRes.RenameFile, Tag = "RenameFile", Icon = MainUserControl.Resources["ImgRename"] };
                menuitem.Click += FileMenuClick;
                contextMenu.Items.Add(menuitem);
            }
            item.ContextMenu = contextMenu;
            contextMenu.IsOpen = true;
        }

        private void FileMenuClick(object sender, RoutedEventArgs e)
        {
            var ids = ((FrameworkElement)TreeView.SelectedItem).Tag.ToString();
            var command = ((FrameworkElement)sender).Tag.ToString();

            CelPhoneMsg.Text = AppRes.WaitCommand;
            IsEnabled = false;

            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() => CommmandMenuExplorer(command, ids, (TreeViewWithIcons)TreeView.SelectedItem)));
        }

        private static void PreviewFileMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = (TreeViewItem)sender;
            item.Focus();
            item.IsSelected = true;
        }

        private void ChangeBntConnect()
        {
            if (Package.PhoneDevice.Connected)
            {
                BntConnect.Visibility = Visibility.Collapsed;
                BntDisconnect.Visibility = Visibility.Visible;
                DeviceLeft.Visibility = Visibility.Collapsed;
                var mark = ((TreeViewWithIcons)TreeView.Items[0]).Checked ?? false;
                ActCopysel.IsEnabled = mark;
                ActDeletesel.IsEnabled = mark;
                if (mark)
                {
                    ActCopysel.Foreground = VsTheming.GetWindowText();
                    ActDeletesel.Foreground = VsTheming.GetWindowText();
                }
                else
                {
                    ActCopysel.Foreground = VsTheming.GetWindowDisabledText();
                    ActDeletesel.Foreground = VsTheming.GetWindowDisabledText();
                }
            }
            else
            {
                BntConnect.Visibility = Visibility.Visible;
                BntDisconnect.Visibility = Visibility.Collapsed;
                DeviceLeft.Visibility = Visibility.Visible;
                ActCopysel.IsEnabled = false;
                ActDeletesel.IsEnabled = false;
                ActCopysel.Foreground = VsTheming.GetWindowDisabledText();
                ActDeletesel.Foreground = VsTheming.GetWindowDisabledText();
            }
        }

        private void BntDisconnectClick(object sender, RoutedEventArgs e)
        {
            CelPhoneMsg.Text = AppRes.WaitDisconnecting;
            BntDisconnect.IsEnabled = false;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(TryDisconnectCallBack));
        }

        private void TryDisconnectCallBack()
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            CelPhoneMsgErro.Text = string.Empty;
            CelPhoneMsgErro.Visibility = Visibility.Collapsed;
            if (Package.PhoneDevice != null)
            {
                Package.PhoneDevice.Disconnect();
            }
            ShowInfoEnvDevice();
            ChangeBntConnect();
            LoadTreeViewDevice();
            BntDisconnect.IsEnabled = true;
            if (Package.PhoneDevice != null && Package.PhoneDevice.Connected)
            {
                Timer.Start();
            }
            else
            {
                Timer.Stop();
            }
            Cursor = oldcur;
        }

        private void DeviceLeftMouseLefttButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!Package.PhoneDevice.Connected)
            {
                Package.PhoneDevice.CurrentConnectableDevice = ChangeDevice(false);
                CelPhoneManufature.Text = Package.PhoneDevice.Name;
            }
        }

        private void XapDeployDialogMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            var dialogXapDeploy = new XapDeployDialog { ParentWindow = this };
            dialogXapDeploy.ShowModal();
            Cursor = oldcur;
        }

        private void DeviceLeftMouseEnter(object sender, MouseEventArgs e)
        {
            if (!Package.PhoneDevice.Connected)
            {
                DeviceLeft.Source = new BitmapImage(
                        new Uri(Constants.RootResource + Constants.RotateOn,
                                UriKind.RelativeOrAbsolute));
                CelPhoneManufature.Foreground = VsTheming.GetWindowHighlightText();
            }
        }

        private void DeviceLeftMouseLeave(object sender, MouseEventArgs e)
        {
            if (!Package.PhoneDevice.Connected)
            {
                DeviceLeft.Source = new BitmapImage(
                    new Uri(Constants.RootResource + Constants.RotateOff,
                            UriKind.RelativeOrAbsolute));
                CelPhoneManufature.Foreground = VsTheming.GetWindowText();
            }
        }

        private void MenutranslClick(object sender, RoutedEventArgs e)
        {
            var project = EnvPhoneDevice.GetCurrentProject(Package.EnvDte);
            if (project == null && Package.TotalProjects == 1 && Package.TotalPhoneProjects > 0)
            {
                project = Package.EnvDte.Solution.Projects.Item(1);
            }
            if (project == null)
            {
                MessageBox.Show(AppRes.ErrSolutionCreateLoaction);
                return;
            }
            var ivsol = Package.GetServiceHelper(typeof(SVsSolution)) as IVsSolution;
            if (!EnvPhoneDevice.IsPhoneProject(ivsol, project))
            {
                MessageBox.Show(AppRes.ErrSolutionCreateLoaction);
                return;
            }

            var prjid = EnvPhoneDevice.GetProjectGuid(ivsol, project);

            var window = (WpcTranslteToolWindow)Package.CreateWindow<WpcTranslteToolWindow>(Math.Abs(prjid.ToString().GetHashCode() - PkgCmdIDList.cmdidTranslateResx.GetHashCode()));

            window.OwnerProject = project.Name;
            window.NeutralResource = EnvPhoneDevice.GetNeutralResourcesLanguage(project);
            window.SelectedResource = null;
            WindowsPhoneCommandsPackage.ShowWindow(window);
        }

        private static void BwDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = Common.CheckVersion("version");
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch { }
            // ReSharper restore EmptyGeneralCatchClause
        }

        private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((Boolean)e.Result)
            {
                BntUpdated.Visibility = Visibility.Visible;
                _updatedStoryboard.Begin(this);
            }
            else
            {
                BntUpdated.Visibility = Visibility.Hidden;
            }
        }

        private void UserPropertiesClick(object sender, RoutedEventArgs e)
        {
            var dialog = new UserSettingsDialog();
            dialog.ShowModal();
        }

        private void HelpClick(object sender, RoutedEventArgs e)
        {
            var dialog = new AboutDialog();
            dialog.ShowModal();
        }

        private void BntUpdatedClick(object sender, RoutedEventArgs e)
        {
            Process.Start("http://wphonecommands.codeplex.com");
        }

        #endregion


    }
}